package com.liumuxian.video.service.impl;


import com.liumuxian.video.dao.AdvertisingDao;
import com.liumuxian.video.pojo.Advertising;
import com.liumuxian.video.service.AdvertisingService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import util.IdWorker;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
@Transactional(readOnly = true)
public class AdvertisingServiceImpl implements AdvertisingService {
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private AdvertisingDao advertisingDao;
    @Transactional
    public void save(Advertising advertising){
        advertising.setId(idWorker.nextId()+"");
        advertising.setCreatdata(new Date());
        advertising.setState(1);
        advertisingDao.save(advertising);
    }
    @Transactional
    public void update(Advertising advertising){
        Advertising advertising1 = advertisingDao.findById(advertising.getId()).get();
        BeanUtils.copyProperties(advertising,advertising1);
        advertising1.setUpdatedate(new Date());
        advertisingDao.saveAndFlush(advertising);
    }
    @Transactional
    public void delete(String id){
        Advertising advertising = advertisingDao.findById(id).get();
        advertising.setUpdatedate(new Date());
        advertising.setState(0);
        advertisingDao.saveAndFlush(advertising);
    }
    public Advertising findById(String id){
        return advertisingDao.findById(id).get();
    }

    public List<Advertising> findAllGesTate(String id,String title,Integer state) {
        return advertisingDao.findAll((Root<Advertising> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) -> {
            List<Predicate> predicateList = new ArrayList<Predicate>();
            if (id != null && !StringUtils.isEmpty(id)) {
                predicateList.add(criteriaBuilder.equal(root.get("id"), id));
            }
            if (title != null && !StringUtils.isEmpty(title)) {
                predicateList.add(criteriaBuilder.like(root.get("title"), "%" + title + "%"));
            }
            if (state != null && !StringUtils.isEmpty(state)) {
                predicateList.add(criteriaBuilder.ge(root.get("state"), (Number) state));
            }
            return criteriaBuilder.and( predicateList.toArray(new Predicate[predicateList.size()]));
        });
    }

}
